package com.zyf.lj.controller;

import com.zyf.lj.entity.User;
import com.zyf.lj.service.UserService;
import com.zyf.lj.util.JwtUtil;
import com.zyf.lj.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 获取用户信息
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/{id}")
    public Result<User> getUser(@PathVariable Long id) {
        User user = userService.getUserById(id);
        if (user != null) {
            return Result.success(user);
        }
        return Result.fail("用户不存在");
    }
    
    /**
     * 获取所有用户
     * @return 用户列表
     */
    @GetMapping("/list")
    public Result<List<User>> getAllUsers() {
        List<User> users = userService.getAllUsers();
        return Result.success(users);
    }
    
    /**
     * 新增用户
     * @param user 用户信息
     * @return 结果
     */
    @PostMapping
    public Result<Void> addUser(@RequestBody User user) {
        if (userService.addUser(user)) {
            return Result.success();
        }
        return Result.fail("添加用户失败");
    }
    
    /**
     * 更新用户
     * @param user 用户信息
     * @return 结果
     */
    @PutMapping
    public Result<Void> updateUser(@RequestBody User user) {
        if (userService.updateUser(user)) {
            return Result.success();
        }
        return Result.fail("更新用户失败");
    }
    
    /**
     * 删除用户
     * @param id 用户ID
     * @return 结果
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        if (userService.deleteUser(id)) {
            return Result.success();
        }
        return Result.fail("删除用户失败");
    }
    
    /**
     * 微信登录
     * @param loginRequest 包含微信登录code和用户信息的请求体
     * @return 用户信息和令牌
     */
    @PostMapping("/wx-login")
    public Result<Map<String, Object>> wxLogin(@RequestBody Map<String, Object> loginRequest) {
        try {
            String code = (String) loginRequest.get("code");
            
            if (code == null) {
                log.warn("微信登录请求中code为空");
                return Result.fail("微信登录code不能为空");
            }
            
            log.info("收到微信登录请求，code: {}", code);
            
            // 获取微信用户加密信息
            String rawData = (String) loginRequest.get("rawData");
            String signature = (String) loginRequest.get("signature");
            String encryptedData = (String) loginRequest.get("encryptedData");
            String iv = (String) loginRequest.get("iv");
            
            // 获取微信用户信息（如果有）
            @SuppressWarnings("unchecked")
            Map<String, Object> wxUserInfo = null;
            if (rawData != null) {
                wxUserInfo = new HashMap<>();
                wxUserInfo.put("rawData", rawData);
                wxUserInfo.put("signature", signature);
                wxUserInfo.put("encryptedData", encryptedData);
                wxUserInfo.put("iv", iv);
            }
            
            // 调用微信登录服务
            User user = userService.wxLogin(code, wxUserInfo);
            
            if (user != null) {
                // 生成JWT令牌
                String token = jwtUtil.generateToken(user.getId(), user.getOpenid());
                
                // 构建返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("token", token);
                result.put("userInfo", user);
                
                log.info("微信登录成功，用户ID: {}, openid: {}", user.getId(), user.getOpenid());
                return Result.success(result);
            }
            
            log.warn("微信登录失败，用户信息为空");
            return Result.fail("微信登录失败，请稍后重试");
        } catch (Exception e) {
            log.error("微信登录异常: {}", e.getMessage(), e);
            return Result.fail("微信登录处理异常: " + e.getMessage());
        }
    }
} 